package com.efounder.chat.utils;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.core.xml.StubObject;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.model.AppConstant;
import com.efounder.chat.model.Group;
import com.efounder.chat.model.GroupRootBean;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.service.Registry;
import com.efounder.util.AbFragmentManager;
import com.pansoft.library.utils.LogUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;

import static com.efounder.chat.http.JFCommonRequestManager.TYPE_GET;

/**
 * ChatActivity 和 JFChatActivity中使用的chatConfig
 * @author zzj
 */
public class ChatConfigUtil {
    private static final String CHAT_CONFIG_TAG = "chatConfig";
    private static ChatConfigUtil instance = new ChatConfigUtil();
    private ChatConfigUtil(){

    }
    public static ChatConfigUtil getInstance() {
        return instance;
    }

    public void getChatConfig(final Context context, final LinearLayout llMenu, final Group group){
        String userId = EnvironmentVariable.getProperty(Constants.CHAT_USER_ID);
        String passWord = EnvironmentVariable.getProperty(Constants.CHAT_PASSWORD);
        if (null != group) {
            int groupId = group.getGroupId();
//            String url = "http://im.solarsource.cn:9692/IMServer/group/getConfig?userId=%s&passWord=%s&groupId=%s&configKey=groupChatIcon";
//            String urlPath = String.format(url, userId, passWord, groupId);
            String url = "http://im.solarsource.cn:9692/IMServer/group/getConfig";
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("userId", userId);
            hashMap.put("passWord", passWord);
            hashMap.put("groupId", groupId+"");
            hashMap.put("configKey", "groupChatIcon");
            JFCommonRequestManager.getInstance(context).requestAsyn(CHAT_CONFIG_TAG,url,TYPE_GET,hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
                @Override
                public void onReqSuccess(String result) {
                    //数据解析
                    parseData(context,group,llMenu,result);
                }

                @Override
                public void onReqFailed(String errorMsg) {
                    LogUtils.e("ChatConfigUtil" + ":getChatConfig.exception=" + errorMsg);
                }
            });

        }
    }

    /**
     * 取消数据请求
     * @param context
     */
    public void cancleRequest(Context context){
        JFCommonRequestManager.getInstance(context).cannelOkHttpRequest(CHAT_CONFIG_TAG);
    }
    /**
     * 解析数据
     */
    private void parseData(final Context context, final Group group, LinearLayout llMenu, String json){
//        String json = new String(bytes);
        try {
            JSONObject object = new JSONObject(json);
            if (object == null) {
                return;
            }
            if (!object.has("result")) {
                return;
            }
            String result = object.getString("result");
            if ("success".equals(result)) {
                if (!object.has("configValue")) {
                    return;
                }
                String value = object.getString("configValue");
                if (null != value) {
//                            "configValue":"punchcard|common"
                    LogUtils.e("configValue=" + value);
                    List<StubObject> officeRoot = Registry.getRegEntryList("GroupRoot");
//                            final ArrayList<String> typeList = new ArrayList<>();
//                            final ArrayList<String> activityList = new ArrayList<>();
//                            final ArrayList<String> iconList = new ArrayList<>();
                    /*展示在titleBar上的快捷按钮容器*/
                    final List<GroupRootBean> groupMenuList = new ArrayList<>();
                    for (int i = 0; i < officeRoot.size(); i++) {
                        StubObject stubObject = officeRoot.get(i);
                        Hashtable stubTable = stubObject.getStubTable();

                        String id = (String) stubTable.get("chatUserId");
                        if (value.contains(id)) {
                            GroupRootBean bean = new GroupRootBean();
                            bean.setIcon((String) stubTable.get("icon"));
                            bean.setViewType((String) stubTable.get("viewType"));
                            bean.setShow((String) stubTable.get("AndroidShow"));
                            groupMenuList.add(bean);
                        }
                    }
                    if (groupMenuList != null && groupMenuList.size() > 0) {
                        //清除view
                        if(llMenu!=null){
                            llMenu.removeAllViews();
                        }
                        for (int i = 0; i < groupMenuList.size(); i++) {
                            String filepath = AppConstant.APP_ROOT + "/res" + "/" + "unzip_res" + "/" + "menuImage/" + groupMenuList.get(i).getIcon();
                            ImageView iv = new ImageView(context);
                            if (!TextUtils.isEmpty(filepath))
//                                            imageLoader.displayImage("file://" + filepath, iv, options);
                                LXGlideImageLoader.getInstance().displayImage(context, iv, "file://" + filepath);
                            final int finalI = i;
                            iv.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if ("group_function_2_".equals(groupMenuList.get(finalI).getIcon())) {
                                        String viewType = groupMenuList.get(finalI).getViewType();
                                        if (null != viewType)
                                            if ("display".equals(viewType)) {
//                                                    跳转页面
                                                String aName = groupMenuList.get(finalI).getShow();
                                                AbFragmentManager abFragmentManager = new AbFragmentManager(context);
                                                StubObject stubObject = new StubObject();
                                                Hashtable<String, String> hashtable = new Hashtable<String, String>();
                                                hashtable.put("groupId", group.getGroupId() + "");
                                                hashtable.put("groupName", group.getGroupName());
                                                hashtable.put("AndroidShow", aName);
                                                stubObject.setStubTable(hashtable);
                                                try {
                                                    abFragmentManager.startActivity(stubObject, 0, 0);
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                                           /* //显示意图
//                                                    Intent intent = new Intent(ChatActivity.this, WorkCardActivity.class);
                                                            Intent intent = new Intent();
//                                                    intent.setClass(ChatActivity.this, WorkCardActivity.class);
//                                                    隐式意图
                                                            String packageName;
                                                            packageName = "com.efounder.chat";
                                                            if (!TextUtils.isEmpty(aName)) {
                                                                ComponentName componentName = new ComponentName(ChatActivity.this, packageName + ".activity." + aName);
                                                                intent.setComponent(componentName);
                                                                intent.putExtra("groupName", group.getGroupName());
                                                                intent.putExtra("groupId", group.getGroupId());
                                                                startActivity(intent);
                                                            }*/
                                            } else if ("webView".equals(viewType)) {
//                                                    webview 展示

                                            }
                                    }
                                }
                            });

                            llMenu.addView(iv);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
